#coding:utf-8
from alipay import AliPay
import time,os,sys,json
from app import db
from app.home import home
from flask import request, jsonify,session,g,current_app
from app.models import Goods,Article,Order,GoodsImg
from response_code import RET
from ..func.gengerate_order_id import generate_order_id

#--------------------------商品前端接口----------------------------------------
#展示商品列表   分类   商品
@home.route("/goods",methods=["GET"])
def goods():
    goods_sort=request.args.get("goods_sort")     #分类
    # print(goods_sort)
    if not goods_sort:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.PARAMERR,msg="参数错误")
    try:
        goods_data = db.session.query(Goods.id,Goods.name,Goods.danjia,Goods.kucun,Goods.sell_num).filter(Goods.sort==goods_sort).all()
    except:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.OK,msg="数据库查询失败",data="")

    return jsonify(code=RET.OK,msg="获取商品列表成功",goods_data=goods_data)

#展示商品详情
@home.route("/goodsinfo",methods=["GET"])
def goodsinfo():
    goods_id=request.args.get("id")     #分类
    # print(goods_id)
    if not goods_id:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.PARAMERR,msg="参数错误")
    try:
        goods_data = db.session.query(Goods.id,Goods.name,Goods.danjia,Goods.kucun,Goods.sell_num,Goods.miaoshu,Goods.sort).filter(Goods.id==goods_id).first()
    except:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.OK,msg="数据库查询失败",data="")
    current_app.logger.error(sys._getframe().f_code.co_name)
    return jsonify(code=RET.OK,msg="获取商品列表成功",goods_data=goods_data)

#-------------------------------------------订单生成-------------------------------------------------------------------
#生成订单
@home.route("/orders",methods=["post"])
def orders():
    goods_id=request.form.get("id")
    goods_num=request.form.get("goods_num")
    if not all([goods_id,goods_num]):
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.PARAMERR,msg="参数错误")
    try:
        goods=db.session.query(Goods.id,Goods.name,Goods.kucun,Goods.danjia).filter(Goods.id == goods_id).first()
    except:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.DBERR,msg="数据库查询失败",data="")

    if not goods:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.NODATA, msg="此商品不存在", data="")
    if goods.kucun < 5:
        return jsonify(code=RET.DATAERR, msg="此商品库存不足", data="")
    order_id = generate_order_id()
    orders = Order(
        order_id=order_id,
        name=goods.name,  # 标题
        danjia=goods.danjia,  # 单价
        num=goods_num,  # 库存
        goods_id=goods_id,
        addtime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    db.session.add(orders)
    db.session.commit()
    try:
        db.session.add(orders)
        db.session.commit()
    except:
        db.session.rollback()
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.DBERR, msg="数据库保存订单失败", data="")
    # goods_amount=(int(goods.danjia)/100.00)*goods_num
    goods_amount = int(goods.danjia) * int(goods_num)*1.00
    order_data={
        "order_id":order_id,
        "goods_id":goods_id,
        "goods_name":goods.name,
        "goods_num":goods_num,
        "goods_amount":goods_amount
    }
    return jsonify(code=RET.OK,msg="订单创建成功",goods_data=order_data)



    try:
        goods_data = db.session.query(Goods.id,Goods.name,Goods.danjia,Goods.kucun,Goods.sell_num,Goods.miaoshu,Goods.sort).filter(Goods.id==goods_id).first()
    except:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.OK,msg="数据库查询失败",data="")
    current_app.logger.error(sys._getframe().f_code.co_name)
    return jsonify(code=RET.OK,msg="获取商品列表成功",goods_data=goods_data)
#-------------------------------------------订单支付-------------------------------------------------------------------
app_id = "2016102600765547"

# app_private_key_string = '-----BEGIN PRIVATE KEY-----\n' + app_private_key_string + '\n-----END PRIVATE KEY-----'
# alipay_public_key_string = '-----BEGIN PUBLIC KEY-----\n' + alipay_public_key_string + '\n-----END PUBLIC KEY-----'
test_url = "https://openapi.alipaydev.com/gateway.do"  # 沙箱环境支付宝支付接口
url = "https://openapi.alipay.com/gateway.do"  # 支付宝支付接口


@home.route("/pay", methods=["POST"])
def pay():
    # 接受订单ID，通过订单ID查询订单数据
    # req_data=request.get_json()
    # out_trade_no =req_data.get("out_trade_no")

    # req_data = request.get_json()
    # print(req_data)
    # out_trade_no = req_data.get("out_trade_no")
    # subject = req_data.get("subject")
    # total_amount = req_data.get("total_amount")
    # 创建用于进行支付宝支付的工具对象
    alipay = AliPay(
        appid=app_id,
        app_notify_url=None,  # 默认回调url
        # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥，通过应用公钥在支付宝生成的支付宝公钥
        alipay_public_key_string=open("app/home/keys/alipay_public_key_string.pem").read(),
        # 应用私钥，自己通过工具生成的私钥
        app_private_key_string=open("app/home/keys/app_testapp_private_key.pem").read(),

        sign_type="RSA2",  # RSA 或者 RSA2
        debug=True  # 默认False  配合沙箱模式使用，true为沙箱开发环境
        # debug=False #   正式环境
    )

    # pc网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
    order_string = alipay.api_alipay_trade_page_pay(
        # out_trade_no=out_trade_no,
        # total_amount=total_amount,
        # subject=subject,
        out_trade_no="11334506134421",
        total_amount="0.01",
        subject="购买测试链接，购买前请测试能否正常支付，无法支付请联系客服",
        return_url="http://localhost:8080/payloading",
        notify_url=None,
    )
    # 让用户进行支付的支付宝页面网址
    # url =url+"?"+ order_string
    url = test_url + "?" + order_string
    return jsonify(code=0, url=url)


# 校验支付结果

"""
支付宝会把参数传递给return_url 返回
http://127.0.0.1:5000/orders.html?
charset=utf-8&   编码
out_trade_no=3&   订单id
method=alipay.trade.wap.pay.return&
total_amount=0.01&   金额
sign=AUOC5QZuyZVwQvPVjocUXyR8h9NkINDy8DEtUti%2BWg8Cd1JYitwJZ%2BMeN2Jo6GfBKnmCCjOTSVJSSnfO%2FKbySmy0tHHLB2T%2FBTLKO1x8w0NeN%2Bvk8U6WPktfOgKgV%2B%2FnEMcQ7LmIvudTAF3mBPggufJ00gZM0y1aFbyvDCu2FTMQxOYaJflFmNRC0i6NIbzTzjYEH3dW5b2qB9r%2Fcqb%2F7AxmVAA%2B61s8w%2FeKS%2BO83JGAiQ8epoPY3daPwYeSaAfe7hYryjip3eoIQQAdM3KxihgRGDH%2BvMUTVz69R6iTSjMcAapia4czBAhPbIZXdbwhT3fbNLf1SKkQxVqxNj37dQ%3D%3D&
trade_no=2020052222001458430500991696&  # 支付宝交易流水号
auth_app_id=2016101700711668&
version=1.0&  
app_id=2016101700711668&
sign_type=RSA2&
seller_id=2088102180059499&
timestamp=2020-05-22+13%3A22%3A28
"""


@home.route("/pay_status", methods=["GET", "POST"])
def check_pay():
    # 接受支付宝返回的数据，验证是不是来自支付宝
    data = request.form.to_dict()
    # sign 不能参与签名验证
    signature = data.pop("sign")

    print(json.dumps(data))
    print(signature)

    # verify
    alipay = AliPay(
        appid=app_id,
        app_notify_url=None,  # 默认回调url
        # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥，通过应用公钥在支付宝生成的支付宝公钥
        alipay_public_key_string=open("app/home/keys/alipay_public_key_string.pem").read(),
        # 应用私钥，自己通过工具生成的私钥
        app_private_key_string=open("app/home/keys/app_testapp_private_key.pem").read(),

        sign_type="RSA2",  # RSA 或者 RSA2
        debug=True  # 默认False  配合沙箱模式使用，true为沙箱开发环境
        # debug=False #   正式环境
    )
    success = alipay.verify(data, signature)

    if success:
        # 修改订单信息
        order_id = data.get("out_trade_no")
        trade_no = data.get("trade_no")
        # try:
        #     Order.query.filter_by(id=order_id).update({"status":"WAIT_COMMENT", "trade_no":trade_no})
        #     db.session.commit()
        # except Exception as e:
        #     db.session.rollback()
        #     current_app.logger.error(e)
        #     return jsonify(errno=RET.DBERR, errmsg="数据库异常")
    else:
        return jsonify(code=500, msg="error")
    return jsonify(code=0, msg="ok")














